package com.zhxh.nzpos.setting;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.petpet.sc.widget.SegmentedControl;
import com.zhxh.nzpos.Constants;
import com.zhxh.nzpos.R;
import com.zhxh.nzpos.dao.CategoryDao;
import com.zhxh.nzpos.dao.GoodsDao;
import com.zhxh.nzpos.goods.GoodsItem;
import com.zhxh.nzpos.model.Category;
import com.zhxh.nzpos.model.Goods;
import com.zhxh.nzpos.setting.PriceSettingAdapter.ViewHolder;
import com.zhxh.nzpos.utils.ViewUtil;

/**
 * 价格设定界面
 * 
 * @author wangzt
 * 
 */
public class PriceSettingActivity extends FragmentActivity implements
		ItemActionCallback {
	private ArrayList<GoodsItem> goodsItems;
	private PriceSettingAdapter listAdapter;
	private GoodsDao goodsDao;
	private SegmentedControl tabs;
	private EditText dealOcr;
	private CategoryDao categoryDao;
	private Category cate;
	private ImageView update;
	
	protected static final int PAGESIZE = 15;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_price);
		goodsDao = new GoodsDao(this);
		categoryDao = new CategoryDao(getApplicationContext());
		initViews();
	}

	private void initViews() {
		initTab();
		update = (ImageView)findViewById(R.id.goods_update_btn);
		update.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//商品列表
				  View detailsFrame =findViewById(R.id.details);
				  if (detailsFrame != null) {
					  TextView id =    (TextView)detailsFrame.findViewById(R.id.identifier2);
					
					TextView cate2 =    (TextView)detailsFrame.findViewById(R.id.cate2);
					
					EditText price1 =    (EditText)detailsFrame.findViewById(R.id.price12);
					EditText price2 =    (EditText)detailsFrame.findViewById(R.id.price22);
					
					Goods goods = new Goods();
					goods.setPrice1(Float.parseFloat(price1.getText().toString()));
					goods.setPrice2(Float.parseFloat(price2.getText().toString()));
					
					
					
					goods.setId(id.getText().toString());
					goodsDao.updatePrice(goods);
					
					
			        	//UpdateFragment details = (UpdateFragment)getFragmentManager().findFragmentById(R.id.details);
			        	//if (details == null ) {
					  DetailsFragment details = DetailsFragment.newInstance(cate2.getText().toString());

			        		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			        		ft.replace(R.id.details, details);
			        		ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			        		ft.commit();
			        	//}
			        }
				  update.setVisibility(View.INVISIBLE);
			}
		});

	}

	private void initTab() {

		tabs = (SegmentedControl) findViewById(R.id.cate);

		List<Category> categorys = categoryDao.getAllParents();
		System.out.println("size=" + categorys.size());
		for (int i = 0; i < categorys.size(); i++) {
			Category category = categorys.get(i);

			Button btn = new Button(this);
			btn.setTag(category.getId());
			btn.setId(i);
			btn.setOnClickListener(tabListener);
			btn.setText(category.getCategory());
			btn.setTextSize(20);
			// LayoutParameter
			// tabs.
			LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			if (i == 0) {
				cate = category;
				btn.setBackgroundResource(R.drawable.btn_price_head);
				btn.setPressed(true);

			} else if (i == categorys.size() - 1) {
				btn.setBackgroundResource(R.drawable.btn_price_tail);
				params.leftMargin = -16;
				// params.addRule(RelativeLayout.RIGHT_OF,i-1);
			} else {
				// params.addRule(RelativeLayout.RIGHT_OF,i-1);
				btn.setBackgroundResource(R.drawable.btn_price_midle);
				params.leftMargin = -16;
			}
			// params.addRule(verb)
			tabs.addView(btn, params);
		}

	}

	OnClickListener tabListener = new OnClickListener() {
		public void onClick(View v) {

			String cateid = (String) v.getTag();
	        View titlesFrame = findViewById(R.id.titles);
	        if (titlesFrame != null) {
	        	
	        	
	        	TitlesFragment titles = TitlesFragment.newInstance(cateid);

	        		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
	        		ft.replace(R.id.titles, titles);
	        		ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
	        		ft.commit();
	        	
	        } 
		}
	};

	public void onDelete(int pos) {
		goodsItems.remove(pos);
		listAdapter.notifyDataSetChanged();
	}

	public void search(View view) {
		final EditText dealOcr = (EditText) findViewById(R.id.goods_ocr_et);
		Editable ocr = dealOcr.getText();
		if (ocr != null) {
			String ocrStr = ocr.toString();
			if (goodsItems == null) {
				goodsItems = new ArrayList<GoodsItem>();
			} else {
				goodsItems.clear();

			}
			GoodsDao dao = new GoodsDao(this);
			Goods goods = dao.find(ocrStr.trim());
			if (goods != null) {
				GoodsItem item = copyProperties(goods);
				goodsItems.add(item);
				if (listAdapter != null) {
					listAdapter.notifyDataSetChanged();
				}
			} else {
				ViewUtil.makeToast(this, "没有找到相关商品");
			}
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (resultCode) {
		case RESULT_OK:
			if (requestCode == Constants.SCAN_REQUEST_CODE) {
				if (resultCode == RESULT_OK) {
					String ocrStr = data
							.getStringExtra(Constants.SCAN_RESULT_EXTRA);
					if (!TextUtils.isEmpty(ocrStr)) {
						dealOcr.setText(ocrStr);
					} else {
						Toast.makeText(getApplicationContext(), "请重新扫描！",
								Toast.LENGTH_LONG).show();
					}

				} else if (resultCode == RESULT_CANCELED) {
					Toast.makeText(getApplicationContext(), "请重新扫描！",
							Toast.LENGTH_LONG).show();
				}

			}

		}

	}

	private GoodsItem copyProperties(Goods goods) {
		GoodsItem item = new GoodsItem();
		item.setId(goods.getId());
		item.setCategoryId(goods.getCategoryId());
		item.setCategoryName(goods.getCategoryName());
		item.setName(goods.getName());
		item.setNote(goods.getNote());
		item.setPrice1(goods.getPrice1());
		item.setPrice2(goods.getPrice2());
		item.setSpecification(goods.getSpecification());
		item.setUnits1(goods.getUnits1());
		item.setUnits2(goods.getUnits2());
		item.setPoints(goods.getPonits());
		item.setCode(goods.getCode());
		return item;
	}

	private Goods copyProperties(GoodsItem goods) {
		Goods item = new Goods();
		item.setId(goods.getId());
		item.setCategoryId(goods.getCategoryId());
		item.setCategoryName(goods.getCategoryName());
		item.setName(goods.getName());
		item.setNote(goods.getNote());
		item.setPrice1(goods.getPrice1());
		item.setPrice2(goods.getPrice2());
		item.setSpecification(goods.getSpecification());
		item.setUnits1(goods.getUnits1());
		item.setUnits2(goods.getUnits2());
		item.setCode(goods.getCode());
		item.setPonits(goods.getPoints());
		return item;
	}

	@Override
	public void onUpdate(int position, ViewHolder holder) {
		GoodsItem item = goodsItems.get(position);
		Goods goods = copyProperties(item);

		if (holder.price.getText().toString().length() == 0) {
			holder.price.setError("价格不能为空");
			return;
		}
		if (holder.price2.getText().toString().length() == 0) {
			holder.price2.setError("价格不能为空");
			return;
		}
		if (holder.points.getText().toString().length() == 0) {
			holder.points.setError("积分不能为空");
			return;
		}
		if (holder.unit2.getText().toString().length() == 0) {
			holder.unit2.setError("积分不能为空");
			return;
		}
		goods.setPrice1(Float.parseFloat(holder.price.getText().toString()));
		goods.setPrice2(Float.parseFloat(holder.price2.getText().toString()));
		goods.setPonits(Integer.parseInt(holder.points.getText().toString()));
		goods.setUnits2(holder.unit2.getText().toString());
		int count = goodsDao.update(goods);
		if (count > 0)
			ViewUtil.makeToast(this, "信息保存成功!");
		else {
			ViewUtil.makeToast(this, "信息保存失败，请检查信息录入格式是否正确!");
		}
		// listAdapter.notifyDataSetChanged();

	}
	
//	public void getTitle() {
//		
//	}

}
